from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import time


class UserState(object):
    def __init__(self,
                 user_id,
                 user_name="未知",
                 user_online=None,
                 user_friend=False):
        self.user_id = user_id
        self.user_name = user_name
        self.user_online = user_online
        self.user_friend = user_friend

    def get_str(self):
        if self.user_friend:
            return "%s(%s)[%s]" % (self.user_name, self.user_id, self.get_online_state())
        else:
            return "%s[%s]" % (self.user_id, self.get_online_state())

    def get_online_state(self):
        if self.user_online == None:
            return "未知"
        elif self.user_online == True:
            return "在线"
        elif self.user_online == False:
            return "离线"


class ChatState(object):
    def __init__(self,
                 user_id,
                 user_name,
                 user_session):
        self.user_id = user_id
        self.user_session = user_session
        self.user_name = user_name
        self.rec_text = ""
        self.send_text = ""

    def append_rec(self, text):
        self.rec_text += text

    def set_send_text(self, text):
        self.send_text = text

    def get_str(self):
        return self.user_name


class UserListModel(QAbstractListModel):
    def __init__(self, parent=None):
        super(UserListModel, self).__init__(parent)
        self._data = [UserState("00", "正在加载列表", True, True)]
        # self._data = [UserState("123","张三","在线",True),UserState("456","李四","在线")]

    def rowCount(self, parent=QModelIndex()):
        return len(self._data)

    def data(self, index, role=Qt.DisplayRole, raw=False):
        # 如果当前得索引是不活动得
        if not index.isValid() or not 0 <= index.row() < self.rowCount():
            # 亦或者当前的索引值不在合理范围，即小于等于0，超出总行数
            return QVariant()  # 返回一个QVariant，相当与空条目

        # 从索引取得当前的航号
        row = index.row()

        # 如果当前角色是DisplayRole
        if role == Qt.DisplayRole:
            if raw:
                return self._data[row]
            else:
                # 返回当前行的数据
                return self._data[row].get_str()

        # 如果角色不满足需求，则返回QVariant
        return QVariant()

    def resetFriend(self):
        for u in self._data:
            u.user_friend = False

    def addFriend(self, user_id, user_name):
        flag = False
        for i in range(len(self._data)):
            if self._data[i].user_id == user_id:
                flag = True
                self._data[i].user_friend = True
                self._data[i].user_name = user_name
                break
        return flag

    def setUserListFromId(self, userlist):

        self._data = []
        for u in sorted(userlist):
            self._data.append(UserState(u, user_online=True))

    def getNameFromId(self, user_id):
        for u in self._data:
            if u.user_id == user_id:
                return u.user_name

    def apply(self, setmodel):
        self.beginResetModel()
        setmodel(self)
        self.endResetModel()


class ChatListModel(QAbstractListModel):
    def __init__(self, parent=None):
        super(ChatListModel, self).__init__(parent)
        self._data = []
        # self._data = [UserState("123","张三","在线",True),UserState("456","李四","在线")]

    def rowCount(self, parent=QModelIndex()):
        return len(self._data)

    def data(self, index, role=Qt.DisplayRole, raw=False):
        # 如果当前得索引是不活动得
        if not index.isValid() or not 0 <= index.row() < self.rowCount():
            # 亦或者当前的索引值不在合理范围，即小于等于0，超出总行数
            return QVariant()  # 返回一个QVariant，相当与空条目

        # 从索引取得当前的航号
        row = index.row()

        # 如果当前角色是DisplayRole
        if role == Qt.DisplayRole:
            if raw:
                return self._data[row]
            else:
                # 返回当前行的数据
                return self._data[row].get_str()

        # 如果角色不满足需求，则返回QVariant
        return QVariant()

    def setChat(self, data):
        self._data = []
        for u in data:
            self._data.append(ChatState(u[0], u[1], u[2]))

    def addChat(self, u):
        for user in self._data:
            if user.user_id == u[0]:
                return
        self._data.append(ChatState(u[0], u[1], u[2]))

    def updateRecMessage(self, user_id, message, user_name="我"):
        color='blue'
        if user_name=="我":
            color='darkgreen'
        if user_name=="系统消息":
            color='Chocolate'
        message="    "+message
        record = "<span style=\"color:"+color+"\">"+ user_name+" " + time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) + "</span><br/>" + message+"<br/>"
        for i in range(len(self._data)):
            if self._data[i].user_id == user_id:
                self._data[i].rec_text += record

    def updateSendMessage(self, user_id, message):
        for i in range(len(self._data)):
            if self._data[i].user_id == user_id:
                self._data[i].send_text = message

    def delChat(self, user_id):
        for u in self._data:
            if u.user_id == user_id:
                self._data.remove(u)

    def getDataFromId(self, user_id):
        for u in self._data:
            if u.user_id == user_id:
                return u
